package com.example.mystoryapp2.ui.base

import android.R
import android.os.Bundle
import android.view.MenuItem
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding


/**
 *  the basic activity of others
 *  implement the common method that all the activity may use;
 *  1. define some abstract method: when create a new activity, implement these method can make the
 *  activity have basic function.
 *      * getLayoutId() get the id of layout, only implement this method can build the dataBinding
 *        of this activity easily
 *      * getViewModel() used to bind the viewModel and dataBinding
 *  2. implement some function that every activity may use;
 *      * showBackTitle() show the back button in title bar;
 * @author lv
 */
abstract class BaseActivity<DB: ViewDataBinding, VM: BaseViewModel>:AppCompatActivity() {
    protected lateinit var db:DB
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        db = DataBindingUtil.setContentView(this, getLayoutId())
        db.lifecycleOwner = this
        setViewModel()
        initView()
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    protected fun showBackTitle(){
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.home -> {
                finish()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }


    /**
     * ��ȡ�����ļ�id
     */
    protected abstract fun getLayoutId():Int

    /**
     * ��ȡViewModel
     */
    protected abstract fun getViewModel(): VM

    /**
     * ��ViewModel���ø�dataBinding
     * ִ�� db.viewModel = getViewModels
     */
    protected abstract fun setViewModel()

    protected open fun initView(){
        // nothing to do
    }

}